<template>
	<view class="packageManagementPage">

		<view class="myNmae flex-between">
			<text style="min-width: 100rpx;">套餐标题</text>
			<input v-model="form.name" placeholder="请输入套餐标题" />
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 130rpx;">套餐副标题</text>
			<input v-model="form.desc" placeholder="请输入套餐副标题" />
		</view>
		<view class="myNmae  margin-top_60rpx">
			<text style="min-width: 130rpx;">背景样式</text>
			<view class="margin-top_20rpx " style="margin-left: -120rpx;">
				<radio-group style="transform:scale(0.7)" @change="radioChange" class="flex-start-center">
					<label class="flex-start-center width50" v-for="(item, index) in items" :key="item.value">
						<view>
							<radio :value="item.value" :checked="index === current" />
						</view>
						<view>{{item.name}}</view>
					</label>
				</radio-group>
			</view>
			<view class="margin-top_20rpx">
				<image v-if="!isCustom" class="backgroundImg" :src="backgroundStyle" mode=""></image>
				<sunui-upimg1 v-else class="margin-top_20rpx" :border="'1px dashed #bfbfbf'" :formData="imgFormData"
					:storageMode="storageMode" :header="header" :size="['154rpx', ' 100%']" btnName="上传背景样式"
					:uploadServerUrl="upPicUrl" ref="selectimgandupload1" @uploaded="imgLoaded1" @change="imgsChange1"
					:maxFileNumber="1"><template v-slot:icon>
						<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
					</template></sunui-upimg1>

				<text style="color: rgb(153, 153, 153);">请上传宽690*高188背景图</text>
			</view>
			<view class="margin-top_20rpx">
				<text style="min-width: 100rpx;">LOGO</text>
				<sunui-upimg1 class="margin-top_20rpx" :border="'1px dashed #bfbfbf'" :formData="imgFormData"
					:storageMode="storageMode" :header="header" :size="['154rpx', ' 154rpx']" btnName="上传LOGO"
					:uploadServerUrl="upPicUrl" ref="selectimgandupload2" @uploaded="imgLoaded2" @change="imgsChange2"
					:maxFileNumber="1"><template v-slot:icon>
						<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
					</template></sunui-upimg1>


			</view>
			<view class="myNmae flex-between margin-top_60rpx">
				<text style="min-width: 100rpx;">价格</text>
				<input type="number" v-model="form.price" placeholder="请输入价格" />
			</view>
			<view class="myNmae flex-between margin-top_60rpx">
				<text style="min-width: 100rpx;">次数</text>
				<input ype="number" v-model="form.number" placeholder="请输入次数" />
			</view>

			<!-- 选择规格 -->

			<view class="margin-top_40rpx">
				<view class="flex-between">
					<view class="font-weight_bold">
						说明介绍
					</view>
					<!-- 	<view style="color: rgb(153, 153, 153);" class="">
						请选择
						<uni-icons type="right" size="15"></uni-icons>
					</view> -->

				</view>
				<view style="color: rgb(153, 153, 153);" class="margin-top_20rpx">
					<lRichTextEditor v-model="form.remark" @change="getChange">
					</lRichTextEditor>
				</view>
			</view>
			<view class="btnSure flex" @click="newAdd()">

				{{isEdit?'编辑':'立即添加'}}
			</view>
		</view>
	</view>
</template>

<script>
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		components: {

		},
		data() {
			return {
				tabIndex: 4,

				form: {
					// 套餐标题
					name: '',
					// 套餐副标题
					desc: '',
					// 背景样式
					style: '',
					// 价格
					price: "",
					// 次数
					number: '',
					// 描述说明
					remark: '',
					// LOGO
					logo: '',
					// 样式选择
					style_id: '1'
				},
				imgFormData: null,
				ossInfo: null,
				upPicUrl: null,
				upPicUrl2: null,
				imgStr: [],
				img: [],
				imgStr2: [],
				img2: [],
				
				storageMode: "2",
				isEdit: false,
				header: null,
				isLogo: false,

				items: [{
						value: '1',
						name: '样式一',
						checked: 'true'
					},
					{
						value: '2',
						name: '样式二'
					},
					{
						value: '3',
						name: '样式三'
					},
					{
						value: '4',
						name: '自定义'
					},

				],
				backgroundStyleArr: [
					// '../../static/套餐卡背景/矩形 1590.png',
					// '../../static/套餐卡背景/矩形 1591.png',
					// '../../static/套餐卡背景/组合 907.png'
				   'https://n8.weijuyunke.com/2024-05-28/1139c202405280939213122.png',
				        'https://n8.weijuyunke.com/2024-05-28/e749e202405280940051410.png',
				        'https://n8.weijuyunke.com/2024-05-28/87cb820240528094021945.png'
				],
				current: 0,
				// 是否为自定义
				isCustom: false,
				token: uni.getStorageSync('login').token,
				// 背景样式
				// backgroundStyle: '../../static/套餐卡背景/矩形 1590.png'
				backgroundStyle: 'https://n8.weijuyunke.com/2024-05-28/1139c202405280939213122.png',
			}
		},
		onLoad(options) {
			if (options.id) {
				this.form.id = ''

				this.$sun.assignObject(this.form, {
					...options
				})
				const couponType = this.items.find((item) => {
					return item.value == this.form.style_id
				})

				this.current = Number(couponType.value) - 1
				if (this.current == 3) {
					this.isCustom = true
				}

				this.isEdit = true
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.setItems([options.style]);
				})
				this.$nextTick(() => {
					this.$refs.selectimgandupload2.setItems([options.logo]);
				})

				console.log(this.form)
			}else{
				this.form.style=this.backgroundStyleArr[0]
				this.isEdit = false
			}
		},
		onShow() {
			this.$at.releaseKey('submit');
		},
		methods: {
			// 添加套餐管理
			newAdd() {
				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
						if (!this.form.name) {
							this.$sun.toast("请输入套餐标题", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.desc) {
							this.$sun.toast("请输入套餐副标题", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.logo) {

							this.$sun.toast("请选择logo", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.number) {

							this.$sun.toast("请填写套餐卡次数", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.price) {

							this.$sun.toast("请填写套餐卡价格", 'none')
							this.$at.releaseKey('submit');

						} else if (!this.form.remark) {

							this.$sun.toast("请填写说明介绍", 'none')
							this.$at.releaseKey('submit');

						} else {
							const saveOrUpdate = this.isEdit ? this.$api.editPackage : this.$api.addPackage;
							const res = await this.$http.post({
								url: saveOrUpdate,
								data: {

									...this.form
								},
								headers: {
									'Authorization': `Bearer ${this.token}`
								}

							})
							console.log(res)
							if (res.code == 0) {

								this.$sun.toast(res.msg, 'none')

								// 跳转到登录页面
								this.$at.releaseKey('submit');

								setTimeout(() => {
									this.$sun.navBack()
								}, 500)

							} else {
								this.$at.releaseKey('submit');
								this.$sun.toast(res.msg, 'none')
							}
						}
					}
				});
			},
			radioChange: function(evt) {

				this.form.style_id = evt.detail.value
				if (evt.detail.value == '4') {
					this.isCustom = true
					if(!this.isEdit){
						this.form.style=''
					}
				} else {
					this.isCustom = false
				}


				if (!(evt.detail.value == 4)) {
					this.backgroundStyle = this.backgroundStyleArr[evt.detail.value - 1]
					this.form.style=this.backgroundStyleArr[evt.detail.value - 1]
					console.log(this.backgroundStyle)
				}

			},
			getChange(e) {
				console.log(e)
				this.form.remark = e

			},




			// niuyun
			niuyunLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file)
				let fileUrl = file[i].url;
				this.upPicUrl = this.$api.qnyOssSignature;
				let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
				this.imgFormData = {
					file: fileUrl,
					getsize: file.size,
					getContentType: ['image/png', 'image/jpeg'],
					getoriginalfilename: filesNmae,
					getName: filesNmae
				};
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.upload(); //图片上传
				});
				setTimeout(() => {
					this.niuyunLoop(file, i + 1);
				}, 2500);

			},
			delayLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file.length + '===chand1')
				if (file.length) {
					let fileUrl = file[i].url;
					console.log(fileUrl)
					this.timeDate = new Date().getTime();
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀


					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					if (!this.isLogo) {
						this.$nextTick(() => {
							this.$refs.selectimgandupload1.upload(); //图片上传
						});
					} else {
						this.$nextTick(() => {
							this.$refs.selectimgandupload2.upload(); //图片上传
						});
					}

				} else {
					if (!this.isLogo) {
						this.form.style = ''
					} else {
						this.form.logo = ''
					}
				}

				setTimeout(() => {
					this.delayLoop(file, i + 1);
				}, 500);
			},
			// 上传图片返回
			imgLoaded1(e) {
				console.log(e)

				this.img = [];
				for (let i = 0; i < e.length; i++) {
					this.img.push(e[i].url);
				}


				this.imgStr = this.img

				this.form.style = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},
			// “上传图片”发生改变
			imgsChange1(file) {
				this.isLogo = false
				if (file.length) {
					this.upPicUrl = this.$api.upload;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				} else {
					this.form.style = '',
						this.imgStr = []
				}
			},
			// 上传图片返回
			imgLoaded2(e) {
				console.log(e)

				this.img2 = [];
				for (let i = 0; i < e.length; i++) {
					this.img2.push(e[i].url);
				}


				this.imgStr2 = this.img2

				this.form.logo = this.imgStr2.length === 1 ? this.imgStr2[0].toString() : this.imgStr2
					.join(',');
			},
			// “上传图片”发生改变
			imgsChange2(file) {
				this.isLogo = true
				console.log('上传发生改变this.storageMode1111============', this.storageMode, '参数file', file);
				// 如果是2 上传  阿里云 3  七牛云
				if (file.length) {
					this.upPicUrl = this.$api.upload;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload2.upload(); //图片上传
					});
				} else {
					this.form.logo = '',
						this.imgStr2 = []
				}
			},
			// 阿里云上传
			async userOssSignature(file) {
				// 文件名
				if (file.length) {
					console.log('this阿里云上传进入=======');
					const ts = new Date().getTime();
					const us = {
						ts
					};
					// let url = this.$api.alyOssSignature + `${object2Url(us)}`;
					let url = 'https://yjykmaster.admin168.net/door-massage/massage/upload/alyOssSignature' +
						`${object2Url(us)}`;

					const res = await this.$http.get({
						url: url,
						data: {
							us: us
						}
					});
					this.ossInfo = res.data;
					this.upPicUrl = this.ossInfo?.host;
					// 获取上传图片名称和后缀
					this.delayLoop(file, 0);
				} else {
					this.form.style = '',
						this.imgStr = []
				}




			},

		}
	}
</script>

<style lang="less" scoped>
	.packageManagementPage {

		.btnSure {
			width: 655rpx;
			height: 76rpx;
			background: rgb(81, 142, 247);
			color: rgb(255, 255, 255);
			border-radius: 108rpx;
			font-size: 32rpx;
			font-weight: 700;
			position: fixed;
			bottom: 20rpx;
		}

		padding: 40rpx;
		background-color: #fff;

		.myNmae {

			background-color: #fff;
			min-width: 50rpx;

			.avatar {
				width: 84rpx;
				height: 84rpx;
			}

			input {
				text-align: right;
			}

			.backgroundImg {

				height: 154rpx;


			}

		}
	}

	page {
		background: #f6f6f6;
	}
</style>